﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;
using System.Text;


namespace MII_FIF.Layouts.MII_FIF
{
    public partial class FormDataCabang : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.DataCabangGroupName))
            {
                btnCancel.Click += btnCancel_Click;
                btnSubmit.Click += btnSubmit_Click;
                btnDelete.Click += btnDelete_Click;
                btnAdd.Click += btnAdd_Click;
                GridPrinter.RowEditing += GridPrinter_RowEditing;
                GridPrinter.RowUpdating += GridPrinter_RowUpdating;
                GridPrinter.RowCancelingEdit += GridPrinter_RowCancelingEdit;
                if (!IsPostBack)
                {
                    if (Request.QueryString["ID"] != null)
                    {
                        ((Label)Header.FindControl("lblHeader")).Text = "Add Data Cabang";
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                    }
                    else
                    {
                        ((Label)Header.FindControl("lblHeader")).Text = "View Data Cabang";
                    }
                    Initialize();
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }

        #region Printer
        void btnAdd_Click(object sender, EventArgs e)
        {
            lblError.Text = "";
            bool check = true;
            if (txtJmlPrinter.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please Insert Jumlah Printer. <br />"; check = false;
            }
            else
            {
                int hasil = 0;
                if (!int.TryParse(txtJmlPrinter.Text.Trim(), out hasil))
                {
                    lblError.Text += "Jumlah Printer must a number. <br />"; check = false;
                }
            }
            if (DDLTipePrinter.SelectedIndex == 0)
            {
                lblError.Text += "Please choose Tipe Printer. <br />"; check = false;
            }
            if (check)
            {
                DataTable DTPrinter = (DataTable)ViewState["DTPrinter"];
                DataRow row = DTPrinter.NewRow();
                row["Nama Printer"] = DDLTipePrinter.SelectedItem.Text;
                row["Jumlah"] = txtJmlPrinter.Text;
                row["ID_Printer"] = DDLTipePrinter.SelectedItem.Value;
                row["ID"] = Guid.NewGuid().ToString();
                DTPrinter.Rows.Add(row);
                ViewState["DTPrinter"] = DTPrinter;

                GridPrinter.DataSource = ViewState["DTPrinter"];
                GridPrinter.DataBind();

                txtJmlPrinter.Text = string.Empty;
            }
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            lblError.Text = "";
            bool delete = false;
            DataTable DTPrinter = ((DataTable)ViewState["DTPrinter"]);
            foreach (GridViewRow row in GridPrinter.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk");
                if (chk != null)
                    if (chk.Checked)
                    {
                        delete = true;
                        break;
                    }
            }
            if (delete)
            {
                for (int i = GridPrinter.Rows.Count - 1; i > -1; i--)
                {
                    CheckBox chk = (CheckBox)GridPrinter.Rows[i].FindControl("chk");
                    if (chk != null)
                        if (chk.Checked)
                        {
                            DTPrinter.Rows.RemoveAt(i);
                        }
                }
                GridPrinter.DataSource = DTPrinter;
                GridPrinter.DataBind();
                ViewState["DTPrinter"] = DTPrinter;
            }
            else
            {
                lblError.Text += "Please Choose at least 1 data to delete. <br />";
            }
        }

        void GridPrinter_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
        {
            GridPrinter.EditIndex = -1;
            GridPrinter.DataSource = ((DataTable)ViewState["DTPrinter"]);
            GridPrinter.DataBind();
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        void GridPrinter_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
        {
            lblError.Text = "";
            bool check = true;
            if (((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtJumlahPrinter")).Text.Trim() == string.Empty)
            {
                lblError.Text += "Please Insert Jumlah Printer. <br />"; check = false;
            }
            else
            {
                int hasil = 0;
                if (!int.TryParse(((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtJumlahPrinter")).Text.Trim(), out hasil))
                {
                    lblError.Text += "Jumlah Printer must a number. <br />"; check = false;
                }
            }
            if (((DropDownList)GridPrinter.Rows[e.RowIndex].FindControl("DDLTipePrinter")).SelectedIndex == 0)
            {
                lblError.Text += "Please select Tipe Printer. <br />"; check = false;
            }
            if (check)
            {
                DataTable dt = ((DataTable)ViewState["DTPrinter"]);

                dt.Rows[e.RowIndex]["Nama Printer"] = ((DropDownList)GridPrinter.Rows[e.RowIndex].FindControl("DDLTipePrinter")).SelectedItem.Text;
                dt.Rows[e.RowIndex]["Jumlah"] = ((TextBox)GridPrinter.Rows[e.RowIndex].FindControl("txtJumlahPrinter")).Text;
                dt.Rows[e.RowIndex]["ID_Printer"] = ((DropDownList)GridPrinter.Rows[e.RowIndex].FindControl("DDLTipePrinter")).SelectedItem.Value;

                GridPrinter.EditIndex = -1;
                GridPrinter.DataSource = dt;
                GridPrinter.DataBind();
                ViewState["DTPrinter"] = dt;
                btnAdd.Enabled = true;
                btnDelete.Enabled = true;
                btnCancel.Enabled = true;
                btnSubmit.Enabled = true;
            }
        }

        void GridPrinter_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
        {
            string JumlahPrinter = ((Label)GridPrinter.Rows[e.NewEditIndex].FindControl("lblJumlahPrinter")).Text.ToString();
            string TipePrinter = ((Label)GridPrinter.Rows[e.NewEditIndex].FindControl("lblTipePrinter")).Text.ToString();
            string ID = GridPrinter.Rows[e.NewEditIndex].Cells[4].Text.ToString();

            GridPrinter.EditIndex = e.NewEditIndex;
            GridPrinter.DataSource = ((DataTable)ViewState["DTPrinter"]);
            GridPrinter.DataBind();

            InventoryManagement.Printer Printer = new InventoryManagement.Printer();

            DDLTipePrinter = Generic.BindDDL(DDLTipePrinter, Printer.SelectByParam(), "Title", "ID");
            DropDownList DDLPrinter = ((DropDownList)GridPrinter.Rows[e.NewEditIndex].FindControl("DDLTipePrinter"));
            DDLPrinter = Generic.BindDDL(DDLPrinter, Printer.SelectByParam(), "Title", "ID");

            ((DropDownList)GridPrinter.Rows[e.NewEditIndex].FindControl("DDLTipePrinter")).SelectedIndex = ((DropDownList)GridPrinter.Rows[e.NewEditIndex].FindControl("DDLTipePrinter")).Items.IndexOf(((DropDownList)GridPrinter.Rows[e.NewEditIndex].FindControl("DDLTipePrinter")).Items.FindByValue(ID));

            btnAdd.Enabled = false;
            btnDelete.Enabled = false;
            btnCancel.Enabled = false;
            btnSubmit.Enabled = false;
        }
        #endregion

        void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DataCabang/ViewDataCabang.aspx"));
        }

        void btnSubmit_Click(object sender, EventArgs e)
        {
            lblError.Text = string.Empty;
            if (validasi())
            {
                if (Request.QueryString["ID"] == null)
                {
                    InventoryManagement.Data_Cabang Cabang = PopuplateDataCabang();
                    InventoryManagement.Detail_Printer detailprinter = new InventoryManagement.Detail_Printer();

                    Cabang.Insert();

                    #region detailPrint
                    foreach (GridViewRow row in GridPrinter.Rows)
                    {
                        detailprinter.ID = Guid.NewGuid();
                        detailprinter.ID_Printer = Guid.Parse(row.Cells[4].Text.ToString());
                        detailprinter.Jumlah = int.Parse(((Label)row.FindControl("lblJumlahPrinter")).Text.ToString());
                        detailprinter.ID_DataCabang = Cabang.ID;
                        detailprinter.Insert();
                    }
                    #endregion

                    #region approval
                    InventoryManagement.Approval Apps = new InventoryManagement.Approval();
                    Apps.ID = Guid.NewGuid();
                    Apps.IDChild = Cabang.ID;
                    Apps.URL = Generic.GenLink("/_layouts/MII_FIF/FormApproval/Approval_Cabang.aspx");
                    Apps.Requester = Generic.GetUserLoginReformat();
                    Apps.RequestDate = DateTime.Now;
                    Apps.Modul = "Data Cabang";
                    Apps.Insert();
                    #endregion

                    Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DataCabang/ViewDataCabang.aspx"));
                }
                else
                {
                    InventoryManagement.Data_Cabang Cabang = PopuplateDataCabang();
                    Cabang.Update();

                    InventoryManagement.Detail_Printer detailprinter = new InventoryManagement.Detail_Printer();
                    detailprinter.ID_DataCabang = Cabang.ID;

                    foreach (DataRow row in detailprinter.SelectByParam().Rows)
                    {
                        detailprinter.ID = Guid.Parse(row["ID"].ToString());
                        detailprinter.Delete();
                    }

                    #region detailPrint
                    foreach (GridViewRow row in GridPrinter.Rows)
                    {
                        detailprinter.ID = Guid.NewGuid();
                        detailprinter.ID_Printer = Guid.Parse(row.Cells[4].Text.ToString());
                        detailprinter.Jumlah = int.Parse(((Label)row.FindControl("lblJumlahPrinter")).Text.ToString());
                        detailprinter.ID_DataCabang = Cabang.ID;
                        detailprinter.Insert();
                    }
                    #endregion

                    InventoryManagement.Approval apps = new InventoryManagement.Approval();
                    apps.IDChild = Cabang.ID;
                    apps.Action = word.Approve;
                    DataTable DT = apps.SelectByParam();
                    string approver = DT.Rows[0]["Approver"].ToString();
                    string requester = DT.Rows[0]["Requester"].ToString();
                    //#region sendemail
                    //#region headerEmail
                    //StringDictionary headers = new StringDictionary();
                    //headers.Add("to", Generic.getEmailUser(approver));
                    //headers.Add("cc", "");
                    //headers.Add("bcc", "");
                    //headers.Add("from", "");
                    //headers.Add("subject", "");
                    //headers.Add("content-type", "text/html");
                    //#endregion
                    #region bodyEmail
                    StringBuilder sb = new StringBuilder();
                    sb.Append("test email");
                    Generic.sendEmailSMTP("System@fif.co.id", Generic.getEmailUser(requester), "no SUbject", sb.ToString());
                    #endregion
                    //SPUtility.SendEmail(SPContext.Current.Web, headers, sb.ToString());
                    //#endregion
                    Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DataCabang/ViewDataCabang.aspx"));
                }
            }
        }

        InventoryManagement.Data_Cabang PopuplateDataCabang()
        {
            string ID = Guid.NewGuid().ToString();
            InventoryManagement.Data_Cabang Cabang = new InventoryManagement.Data_Cabang();
            if (Request.QueryString["ID"] != null)
                Cabang.ID = Guid.Parse(Request.QueryString["ID"].ToString());
            else
                Cabang.ID = Guid.Parse(ID);

            Cabang.Alamat = txtALamat.Text;
            Cabang.Bandwidth = int.Parse(DDLBandwidth.SelectedItem.Text);
            Cabang.Date = DateTime.Parse(txtDate.Text);
            Cabang.Engineer = lblEngineer.Text;
            Cabang.HP = txtHP.Text;
            Cabang.ID_NAS = Guid.Parse(DDLTipeNAS.SelectedItem.Value);


            Cabang.ID_Provider = Guid.Parse(DDLProviderNAS.SelectedItem.Value);
            Cabang.ID_Router = Guid.Parse(DDLTipeRouter.SelectedItem.Value);
            Cabang.IPLAN = txtIPLAN.Text;
            Cabang.IPNAS = txtIPNAS.Text;
            Cabang.IPWAN = txtIPWAN.Text;
            Cabang.JumlahNotebook = int.Parse(txtJmlNotebook.Text);
            Cabang.JumlahPC = int.Parse(txtJmlPC.Text);
            Cabang.JumlahTC = int.Parse(txtJmlTC.Text);
            Cabang.KodeCabang = txtKodeCabang.Text;
            Cabang.NamaLokasi = txtNamaLokasi.Text;
            Cabang.NamaCabang = txtNamaCabang.Text;
            Cabang.NamaNAS = txtNamaNAS.Text;
            Cabang.PIC = txtPIC.Text;
            Cabang.SerialNumber = txtSN.Text;
            Cabang.SID = txtSID.Text;
            Cabang.Telp = txtTelp.Text;

            if (Request.QueryString["ID"] == null)
                Cabang.wfStatus = word.WaitingforApproval;
            else
                Cabang.wfStatus = word.Approved;
            //}
            //else
            //{
            //    Cabang.ID = Guid.Parse(Request.QueryString["ID"].ToString());
            //    Cabang.Select();
            //}
            return Cabang;
        }

        void Initialize()
        {
            //lblEngineer.Text = Generic.GetUserLoginReformat();
            InventoryManagement.Printer Printer = new InventoryManagement.Printer();
            InventoryManagement.Provider Provider = new InventoryManagement.Provider();
            InventoryManagement.Router Router = new InventoryManagement.Router();
            InventoryManagement.NAS NAS = new InventoryManagement.NAS();
            InventoryManagement.Approval app = new InventoryManagement.Approval();
            DDLTipePrinter = Generic.BindDDL(DDLTipePrinter, Printer.SelectByParam(), "Title", "ID");
            DDLProviderNAS = Generic.BindDDL(DDLProviderNAS, Provider.SelectByParam(), "Title", "ID");
            DDLTipeNAS = Generic.BindDDL(DDLTipeNAS, NAS.SelectByParam(), "Title", "ID");
            DDLTipeRouter = Generic.BindDDL(DDLTipeRouter, Router.SelectByParam(), "Title", "ID");

            if (Request.QueryString["ID"] != null)
            {
                ViewState["ID"] = Request.QueryString["ID"].ToString();
                InventoryManagement.Data_Cabang Cabang = new InventoryManagement.Data_Cabang();
                InventoryManagement.Detail_Printer Print = new InventoryManagement.Detail_Printer();
                Print.ID_DataCabang = Guid.Parse(ViewState["ID"].ToString());

                app.IDChild = Guid.Parse(ViewState["ID"].ToString());
                DataTable Approval = app.SelectByParam();

                #region cabang
                Cabang.ID = Guid.Parse(ViewState["ID"].ToString());
                Cabang.Select();
                txtDate.Text = Cabang.Date.Value.ToString("dd MMM yyyy");
                lblEngineer.Text = Cabang.Engineer;
                txtALamat.Text = Cabang.Alamat;
                txtNamaCabang.Text = Cabang.NamaCabang;
                txtNamaLokasi.Text = Cabang.NamaLokasi;
                txtNamaNAS.Text = Cabang.NamaNAS;
                txtPIC.Text = Cabang.PIC;
                txtSID.Text = Cabang.SID;
                txtHP.Text = Cabang.HP;
                txtJmlNotebook.Text = Cabang.JumlahNotebook.ToString();
                txtJmlPC.Text = Cabang.JumlahPC.ToString();
                txtJmlTC.Text = Cabang.JumlahTC.ToString();
                txtIPLAN.Text = Cabang.IPLAN;
                txtIPNAS.Text = Cabang.IPNAS;
                txtIPWAN.Text = Cabang.IPWAN;
                txtSN.Text = Cabang.SerialNumber;
                txtTelp.Text = Cabang.Telp;
                txtKodeCabang.Text = Cabang.KodeCabang;
                DDLTipeRouter.SelectedIndex = DDLTipeRouter.Items.IndexOf(DDLTipeRouter.Items.FindByValue(Cabang.ID_Router.ToString()));
                DDLTipeNAS.SelectedIndex = DDLTipeNAS.Items.IndexOf(DDLTipeNAS.Items.FindByValue(Cabang.ID_NAS.ToString()));
                DDLBandwidth.SelectedIndex = DDLBandwidth.Items.IndexOf(DDLBandwidth.Items.FindByValue(Cabang.Bandwidth.ToString()));
                DDLProviderNAS.SelectedIndex = DDLProviderNAS.Items.IndexOf(DDLProviderNAS.Items.FindByValue(Cabang.ID_Provider.ToString()));
                #endregion

                #region printer
                DataTable DT = Print.SelectByParam();
                DT.Columns.Add("Nama Printer", typeof(string));
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    Printer.ID = Guid.Parse(DT.Rows[i]["ID_Printer"].ToString());
                    Printer.Select();
                    DT.Rows[i].BeginEdit();
                    DT.Rows[i]["Nama Printer"] = Printer.Title;
                    DT.Rows[i].AcceptChanges();
                }
                GridPrinter.DataSource = DT;
                GridPrinter.DataBind();
                ViewState["DTPrinter"] = DT;
                #endregion
                ViewState["Requester"] = Approval.Rows[0]["Requester"].ToString();
                if (Approval.Rows[0]["approver"].ToString().ToLower() != Generic.GetUserLoginReformat())
                    DisableControl();
            }
            else
            {
                lblEngineer.Text = SPContext.Current.Web.CurrentUser.Name;
                DataTable DTPrinter = new DataTable();
                DTPrinter.Columns.Add(new DataColumn("Nama Printer", typeof(string)));
                DTPrinter.Columns.Add(new DataColumn("Jumlah", typeof(string)));
                DTPrinter.Columns.Add(new DataColumn("ID", typeof(string)));
                DTPrinter.Columns.Add(new DataColumn("ID_Printer", typeof(string)));
                ViewState["DTPrinter"] = DTPrinter;
            }
        }

        bool validasi()
        {
            bool check = true;
            #region cabang
            if (txtKodeCabang.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Kode Cabang. <br />";
                check = false;
            }
            if (txtNamaCabang.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Nama Cabang. <br />"; check = false;
            }
            if (txtNamaLokasi.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Nama Lokasi. <br />"; check = false;
            }
            if (txtALamat.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Alamat. <br />"; check = false;
            }
            #endregion

            #region date
            if (txtDate.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please choose Date. <br />"; check = false;
            }
            else
            {
                if (DateTime.Parse(txtDate.Text) > DateTime.Now.Date)
                {
                    lblError.Text += "Date must backdated. <br />"; check = false;
                }
            }
            #endregion

            if (txtPIC.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert PIC. <br />"; check = false;
            }
            if (txtIPLAN.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert IP LAN. <br />"; check = false;
            }
            if (txtIPWAN.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert IP WAN. <br />"; check = false;
            }

            #region PC
            if (txtJmlPC.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Jumlah PC. <br />"; check = false;
            }
            else
            {
                int hasil = 0;
                if (!int.TryParse(txtJmlPC.Text, out hasil))
                {
                    lblError.Text += "Jumlah PC must a number. <br />"; check = false;
                }
            }
            #endregion
            #region TC
            if (txtJmlTC.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Jumlah TC. <br />"; check = false;
            }
            else
            {
                int hasil = 0;
                if (!int.TryParse(txtJmlTC.Text, out hasil))
                {
                    lblError.Text += "Jumlah TC must a number. <br />"; check = false;
                }
            }
            #endregion
            #region NAS
            if (txtNamaNAS.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Nama NAS. <br />"; check = false;
            }
            if (txtIPNAS.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert IP NAS.<br />"; check = false;
            }
            #endregion
            #region notebook
            if (txtJmlNotebook.Text.Trim() == string.Empty)
            {
                lblError.Text += "Please insert Jumlah Notebook. <br />"; check = false;
            }
            else
            {
                int hasil = 0;
                if (!int.TryParse(txtJmlNotebook.Text, out hasil))
                {
                    lblError.Text += "Jumlah Notebook must a number. <br />"; check = false;
                }
            }
            #endregion
            if (DDLProviderNAS.SelectedItem.Value == "-1")
            {
                lblError.Text += "Please Select Provider. <br />"; check = false;
            }
            if (DDLTipeNAS.SelectedItem.Value == "-1")
            {
                lblError.Text += "Please Select Tipe NAS. <br />"; check = false;
            }
            if (DDLTipeRouter.SelectedItem.Value == "-1")
            {
                lblError.Text += "Please Select Tipe Router. <br />"; check = false;
            }
            return check;
        }

        void DisableControl()
        {
            txtALamat.Attributes.Add("readonly", "true");
            txtDate.Attributes.Add("readonly", "true");
            txtHP.Attributes.Add("readonly", "true");
            txtIPLAN.Attributes.Add("readonly", "true");
            txtIPNAS.Attributes.Add("readonly", "true");
            txtIPWAN.Attributes.Add("readonly", "true");
            txtJmlNotebook.Attributes.Add("readonly", "true");
            txtJmlPC.Attributes.Add("readonly", "true");
            txtJmlPrinter.Attributes.Add("readonly", "true");
            txtJmlTC.Attributes.Add("readonly", "true");
            txtKodeCabang.Attributes.Add("readonly", "true");
            txtNamaCabang.Attributes.Add("readonly", "true");
            txtNamaLokasi.Attributes.Add("readonly", "true");
            txtNamaNAS.Attributes.Add("readonly", "true");
            txtPIC.Attributes.Add("readonly", "true");
            txtSID.Attributes.Add("readonly", "true");
            txtSN.Attributes.Add("readonly", "true");
            txtTelp.Attributes.Add("readonly", "true");
            btnDelete.Visible = false;
            btnSubmit.Enabled = false;
            btnSubmit.Visible = false;
            btnAdd.Visible = false;
            DDLBandwidth.Enabled = false;
            DDLProviderNAS.Enabled = false;
            DDLTipeNAS.Enabled = false;
            DDLTipePrinter.Enabled = false;
            DDLTipeRouter.Enabled = false;
        }
    }
}
